<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @reset="handleReset" @submit="handleSubmit">
      <template #areaListSelect="{ model, field }">
        <n-select
          v-model:value="model[field]"
          :options="optionsRef"
          clearable
          filterable
          placeholder="选择区服"
        />
      </template>
      <template #anchorSelect="{ model, field }">
        <n-date-picker
          v-model:formatted-value="model[field]"
          clearable
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </template>
    </BasicForm>

    <BasicTable
      ref="actionRef"
      :actionColumn="actionColumn"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      :scroll-x="2048"
      @update:checked-row-keys="onCheckedRow"
    >
      <template #tableTitle>
        <span><b>汇总</b></span> <b>:</b>
        <span style="color: red; margin-left: 10px"
          ><b>{{ totalAmount }}</b></span
        >
      </template>
      <template #toolbar>
        <n-space>
          <n-button v-if="isShowOpt" type="success" @click="batchPass">批量通过</n-button>
          <n-button v-if="isShowOpt" type="error" @click="batchReject">批量驳回</n-button>
          <n-button v-if="isShowOpt" type="warning" @click="batchRefund">批量退还</n-button>
          <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </n-space>
      </template>
    </BasicTable>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { columns } from './columns';
  import { useRouter } from 'vue-router';
  import { getReflectPageList, reflectVerify } from '@/api/reflect/reflectListApi';
  import { formatToDate } from '@/utils/dateUtil';
  import { getAllArea } from '@/api/game/game';
  import { useUserStore } from '@/store/modules/user';

  const schemas: FormSchema[] = [
    {
      field: 'userId',
      component: 'NInput',
      label: '用户ID',
      componentProps: {
        placeholder: '用户ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'roleId',
      component: 'NInput',
      label: '角色ID',
      componentProps: {
        placeholder: '角色ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'money',
      component: 'NInput',
      label: '提现总额',
      componentProps: {
        placeholder: '例：=99、 >99、 <99、 10-99',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'timeRange',
      label: '提现时间',
      componentProps: {
        placeholder: '提现时间',
      },
      slot: 'anchorSelect',
    },
    {
      field: 'userType',
      component: 'NSelect',
      label: '用户类型',
      defaultValue: 0,
      componentProps: {
        options: (function () {
          var arr = [
            {
              label: '全部',
              value: 0,
            },
            {
              label: '玩家',
              value: 1,
            },
            {
              label: '主播',
              value: 2,
            },
          ];
          return arr;
        })(),
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'status',
      component: 'NSelect',
      label: '提现状态',
      defaultValue: 'fail',
      componentProps: {
        options: (function () {
          var arr = [
            {
              label: '待审核',
              value: 'fail',
            },
            {
              label: '已通过',
              value: 'true',
            },
            {
              label: '已驳回',
              value: 'reject',
            },
            {
              label: '已退还',
              value: 'refund',
            },
          ];
          return arr;
        })(),
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const router = useRouter();
  const message = useMessage();
  const dialog = useDialog();
  const actionRef = ref();
  const optionsRef = ref([]);
  const checkedRowKes = ref<any[]>([]);
  const userStore = useUserStore();
  const isShowOpt = userStore.getRoleType == 'admin' || userStore.getRoleType == 'super'; //是否显示操作按钮
  const formParams = reactive({
    userId: 0,
    money: '',
    outNo: '',
    orderNo: '',
    status: '',
    payWay: '',
    type: '',
    timeRange: null,
    pageSize: 10,
    page: 1,
  });
  const actionColumn = reactive({
    width: isShowOpt ? 200 : 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '通过',
            onClick: handlePass.bind(null, record),
            type: 'success',
            ifShow: () => {
              return record.status != 'true' && isShowOpt;
            },
          },
          {
            label: '驳回',
            onClick: handleReject.bind(null, record),
            type: 'error',
            ifShow: () => {
              return record.status != 'true' && isShowOpt;
            },
          },
          {
            label: '退还',
            onClick: handleRefund.bind(null, record),
            type: 'warning',
            ifShow: () => {
              return record.status != 'true' && isShowOpt;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  function onCheckedRow(rowKeys: any[]) {
    checkedRowKes.value = rowKeys;
    console.log('checkedRowKes=', checkedRowKes.value);
  }

  async function handlePass(record: Recordable) {
    console.log('actionColumn=', actionColumn);
    console.log('record=', record);
    record.status = 'true';
    await reflectVerify({ reflectId: record.id.toString(), status: 'true' });
    message.success('通过成功');
    reloadTable();
    // console.log("你点击了通过=",record);
  }

  async function handleReject(record: Recordable) {
    record.status = 'true';
    await reflectVerify({ reflectId: record.id.toString(), status: 'reject' });
    message.success('驳回成功');
    reloadTable();
    // console.log("你点击了驳回=",record);
  }

  async function handleRefund(record: Recordable) {
    record.status = 'true';
    await reflectVerify({ reflectId: record.id.toString(), status: 'refund' });
    message.success('退还成功');
    reloadTable();
    // console.log("你点击了驳回=",record);
  }

  //批量通过
  function batchPass() {
    const anchorIds = unref(checkedRowKes);
    if (anchorIds.length === 0) {
      message.warning('至少选择一条数据');
      return;
    }
    dialog.info({
      title: '提示',
      content: `您确定提现通过？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await reflectVerify({ reflectId: anchorIds.toString(), status: 'true' });
        message.success('批量通过成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  //批量驳回
  function batchReject() {
    const anchorIds = unref(checkedRowKes);
    if (anchorIds.length === 0) {
      message.warning('至少选择一条数据');
      return;
    }
    dialog.info({
      title: '提示',
      content: `您确定提现驳回？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await reflectVerify({ reflectId: anchorIds.toString(), status: 'reject' });
        message.success('批量驳回成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }
  //批量退还
  function batchRefund() {
    const anchorIds = unref(checkedRowKes);
    if (anchorIds.length === 0) {
      message.warning('至少选择一条数据');
      return;
    }
    dialog.info({
      title: '提示',
      content: `您确定提现退还？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await reflectVerify({ reflectId: anchorIds.toString(), status: 'refund' });
        message.success('批量退还成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:5 2xl:4' },
    labelWidth: 76,
    schemas,
  });

  var totalAmount = 0;
  const loadDataTable = async (res) => {
    if (!formParams.userId) {
      formParams.userId = 0;
    } else {
      formParams.userId = parseInt(formParams.userId);
    }
    const param = { ...formParams, ...res };
    console.log("param===", param);
    delete param.makeDate;
    const data = await getReflectPageList(param);
    totalAmount = data.totalAmount; //总金额
    return data;
  };

  function reloadTable() {
    actionRef.value.reload();
  }

  function handleSubmit(values: Recordable) {
    // console.log('submit', values);
    let tempParams = unref(formParams);
    console.log('tempParams', tempParams);
    tempParams = Object.assign(tempParams, values);
    if (values.makeDate) {
      let [startTime, endTime]: [number, number] = values.makeDate;
      let startTimeS = formatToDate(new Date(startTime));
      let endTimeS = formatToDate(new Date(endTime));
      tempParams = Object.assign(tempParams, { startTime: startTimeS, endTime: endTimeS });
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    formParams.status = values.status;
    // console.log('formParams=====', formParams);
    reloadTable();
  }

  onMounted(async () => {
    let areaVal = await getAllArea();
    optionsRef.value = areaVal.map((value) => {
      return {
        label: value.serverName,
        value: value.serverId,
      };
    });
  });
</script>
<style lang="less" scoped></style>
